﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Collections;
using System.Web.Configuration;
using System.Configuration;
using System.Reflection;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
using System.Data;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using System.Runtime.Serialization.Json;

namespace HaiFang
{
    public class WebHelper
    {
        static WebHelper()
        {
        }

        public static string GetVersion()
        {
            //return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            return DateTime.Now.ToString("yyyy-MM-dd hh");
        }

        public static bool CheckUserAuth(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (!context.User.Identity.IsAuthenticated)
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string sJson = jss.Serialize(new AjaxResponse()
                {
                    C = AjaxResponseCode.UnAuthorized
                });
                WriteJson(context, sJson);
                return false;
            }
            return true;
        }

        public static void WriteJsonResult(HttpContext context, object result)
        {
            string sJson=JsonHelper.JsonSerializer<AjaxResponse>(new AjaxResponse()
            {
                C = AjaxResponseCode.Succeed,
                R = result
            });
            WriteJson(context, sJson);
        }

        public static void WriteJsonError(HttpContext context, object error)
        {
            string sJson = JsonHelper.JsonSerializer<AjaxResponse>(new AjaxResponse()
            {
                C = AjaxResponseCode.Failed,
                E = error
            });

            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            WriteJson(context, sJson);
        }

        public static void WriteJson(HttpContext context, string data)
        {
            context.Response.ContentType = "json";
            context.Response.Write(data);
            context.Response.Flush();
        }

        public static SimpleUserInfo GetCurrentUserInfo()
        {
            CustomPrincipal cp = HttpContext.Current.User as CustomPrincipal;
            if (cp != null && cp.Identity != null)
            {
                CustomIdentity ci = cp.Identity as CustomIdentity;
                if (ci != null && ci.UserInfo != null)
                {
                    return ((CustomIdentity)cp.Identity).UserInfo;
                }
            }
            return null;
        }

        public static int GetCurrentUserID()
        {
            int userid = -1;
            SimpleUserInfo sui = GetCurrentUserInfo();
            if (sui != null)
            {
                userid = sui.AutoID;
            }
            return userid;
        }

        public static int GetCurrentUserProjectID()
        {
            int projectid = -1;
            SimpleUserInfo sui = GetCurrentUserInfo();
            if (sui != null)
            {
                projectid = sui.ProjectID;
            }
            return projectid;
        }

        public static void SetUserProjectInfo()
        {
            //设置当前用户的默认项目
            int AutoID = -1;
            ProjectInfo pi = ProxyProjectInfo.QueryProjectInfo(WebHelper.GetCurrentUserID(), 0, 1);
            if (pi != null)
            {
                AutoID = pi.AutoID;
            }
            SimpleUserInfo sui = WebHelper.GetCurrentUserInfo();
            if (sui != null)
            {
                sui.ProjectID = AutoID;
            }
            CustomAuthentication.SetAuthCookie(sui.UserName, sui);
        }

        public static void SetUserProjectInfo(int ProjectID)
        {
            //设置当前用户的默认项目
            SimpleUserInfo sui = WebHelper.GetCurrentUserInfo();
            if (sui != null)
            {
                sui.ProjectID = ProjectID;
            }
            CustomAuthentication.SetAuthCookie(sui.UserName, sui);
        }

        public static void SetUserPassword(string Password)
        {
            //设置当前用户的密码
            SimpleUserInfo sui = WebHelper.GetCurrentUserInfo();
            if (sui != null)
            {
                sui.Password = Password;
            }
            CustomAuthentication.SetAuthCookie(sui.UserName, sui);
        }
    }

    public enum AjaxResponseCode
    {
        Unkown = 0,
        UnAuthorized = 1,
        Succeed = 2,
        Failed = 3
    }

    public class AjaxResponse
    {
        /// <summary>
        /// Code
        /// </summary>
        public AjaxResponseCode C { get; set; }

        /// <summary>
        /// Result
        /// </summary>
        public object R { get; set; }

        /// <summary>
        /// Error
        /// </summary>
        public object E { get; set; }
    }
}


/// </summary>
public class JsonHelper
{
    public static string JsonSerializer<T>(T t)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = int.MaxValue;
        string jsonString=jss.Serialize(t);

        //替换Json的Date字符串
        string p = @"\\/Date\(\-*\d+\)\\/";
        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
        Regex reg = new Regex(p);
        jsonString = reg.Replace(jsonString, matchEvaluator);
        return jsonString;
    }
    public static T JsonDeserialize<T>(string jsonString)
    {
        string p = @"\\/Date\(\-*\d+\)\\/";
        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
        Regex reg = new Regex(p);
        jsonString = reg.Replace(jsonString, matchEvaluator);

        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = int.MaxValue;
        T obj = jss.Deserialize<T>(jsonString);

        return obj;
    }
    private static string ConvertJsonDateToDateString(Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        string sdate=m.Groups[0].Value;
        int ibegin=sdate.IndexOf('(');
        int iend=sdate.IndexOf(')');
        dt = dt.AddMilliseconds(long.Parse(sdate.Substring(ibegin + 1, iend-ibegin-1)));
        if (dt != DateTime.MinValue)
        {
            dt = dt.ToLocalTime();
        }
        result = dt.ToString("yyyy-MM-dd HH:mm:ss");
        return result;
    }
    //暂时不使用
    private static string ConvertDateStringToJsonDate(Match m)
    {
        string result = string.Empty;
        DateTime dt = DateTime.Parse(m.Groups[0].Value);
        dt = dt.ToUniversalTime();
        TimeSpan ts = dt - DateTime.Parse("1970-01-01");
        result = string.Format("\\/Date({0})\\/", ts.TotalMilliseconds);
        return result;
    }
}